using System;
using System.ServiceModel;
using System.Web;

namespace DynamicConfigurationManager.ConfigMapAttributes
{
    internal class WebUrl : IConfigMapAttribute
    {
        public bool Execute( string configMapAttribute )
        {
            int port;
            string hostname;
            if( OperationContext.Current != null
                && OperationContext.Current.Channel != null
                && OperationContext.Current.Channel.LocalAddress != null
                && OperationContext.Current.Channel.LocalAddress.Uri != null )
            {
                var uri = OperationContext.Current.Channel.LocalAddress.Uri;
                LogHelper.Append( "OperationContext.Current.Channel.LocalAddress.Uri: {0}", uri );
                hostname = uri.Host;
                port = uri.Port;
            }
            else if( HttpContext.Current != null )
            {
                var reqUri = HttpContext.Current.Request.Url;
                LogHelper.Append( "HttpContext.Current.Request.Url: {0}", reqUri );
                hostname = reqUri.Host;
                port = reqUri.Port;
            }
            else
            {
                LogHelper.Append( "Error: Unknown Request Context" );
                throw new ApplicationException( "Unknown Request Context" );
            }

            var mWebUrl = hostname + ( port == 80 ? string.Empty : ":" + port );
            return mWebUrl.Equals( configMapAttribute, StringComparison.OrdinalIgnoreCase );
        }
    }
}